import cp from 'node:child_process'

import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'

// const __dirname = dirname(fileURLToPath(import.meta.url))

// 启动子进程
export function fork(script, params = [], options) {
  // const script = resolve(__dirname, options.path);
  // const script = resolve(__dirname, options.path);
  const child = cp.fork(script, params)

  //   let invoked = false

  //   child.on('message', data => {
  //     options?.message(data)
  //   })

  // child.on('exit', code => {
  //   console.log('[for] exit', code)
  //   options?.exit()
  //   // if (invoked) return
  //   // invoked = true
  //   // options?.exit(code)
  // })

  // child.on('error', err => {
  //   console.log('[for] error', err)
  //   // if (invoked) return
  //   // invoked = true
  //   // options?.error(err)
  // })

  return child
}

export async function watchDog(script, params = process.argv.slice(2), restartDelay = 30 * 1000) {
  const child = fork(script, params)

  child.on('exit', code => {
    if (code === 0) return

    // 自动重启
    console.log(`[watchDog] 运行异常，${restartDelay / 1000}秒后重新运行`)

    setTimeout(() => watchDog(script, params), restartDelay)
  })
}
